var _CONFIG = {
    TYPE: "",
    JQXGRID: '#jqx_grid_view',
    BINDING_URI: base_url + 'cms/cp/lookbook/binding_by_type/',
    EDITPANEL_URI: base_url + 'cms/cp/lookbook/editpanel/',
    COMMIT_URI: base_url + 'cms/cp/lookbook/oncommit/',
    DELETE_URI: base_url + 'cms/cp/lookbook/ondelete/',
};

var _CP = (function() {
    var oTable;
    var that = this;
    var datafields = [
        {name: 'lookbook_id', type: 'int'},
        {name: 'lookbook_title'},
        {name: 'lookbook_image'},
        {name: 'lookbook_position', type: 'int'},
        {name: 'lookbook_status', type: 'bool'},
        {name: 'lookbook_insert', type: 'date'},
        {name: 'lookbook_update', type: 'date'},
    ];
    var source, dataAdapter;
    return {
        onCommit: function(Params, Id, callback) {
            /* Commit data lên vào DB, Id>0 là Update, Id=0 hoặc ko có là Insert */
            backend({
                url: _CONFIG.COMMIT_URI,
                data: {
                    Id: Id,
                    Params: Params
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    } else {
                        $.jGrowl(rsdata.message);
                        if (typeof callback == 'function') {
                            callback();
                        }
                    }
                }
            }).call();
        },
        creategrid: function() {

            source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.BINDING_URI + _CONFIG.TYPE,
                id: 'block_id',
                root: 'rows',
            };
            dataAdapter = new $.jqx.dataAdapter(source, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
            var columns = [
                {
                    text: '', dataField: 'lookbook_id', width: 60, filterable: false, sortable: false, editable: false,
                    cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) {
                        var str = "";
                        if (value && value > 0) {
                            try {
                                //value = $.parseJSON(value);
                                str += "\
                                    <span style='margin: 4px 4px 4px 12px; float: left;' class=\"icon-pencil\" onclick=\"_CP.onEditItem(" + value + ");\"  title='Edit:" + value + "'></span>\
                                ";
                                str += "\
                                    <span style='margin: 4px; float: left;' class='icon-trash' onclick=\"_CP.onDeleteItem(" + value + ");\" title='Delete:" + value + "'></span>\
                                ";
                            } catch (e) {
                            }
                        }

                        return str;
                    }
                },
                {
                    text: 'TITLE', dataField: 'lookbook_title', minWidth: 220
                },
                {
                    text: 'IMAGE', dataField: 'lookbook_image', width: 60,
                    filterable: false, sortable: false, editable: false,
                    cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) {
                        if (value == undefined || value == '')
                            return '';
                        else {

                            return '<img onError="this.src = \'/libraries/images/22/picture.png\'" class="cellthumb" height="32" src="' + value + '"/>';
                        }
                    }
                },
                {
                    text: 'POSITION', dataField: 'lookbook_position',
                    width: 60, cellsalign: 'right',
                    filterable: false, sortable: false, editable: true,
                    columntype: 'numberinput', filtertype: 'number',
                    validation: function(cell, value) {
                        if (value < 0 || value > 99) {
                            return {result: false, message: "Position should be in the 0-99 interval."};
                        }
                        return true;
                    }
                },
                {
                    text: 'STATUS', dataField: 'lookbook_status', cellsalign: 'center',
                    width: 60, columntype: 'checkbox', threestatecheckbox: false,
                    filterable: false, sortable: false, editable: true
                },
                {
                    text: 'CREATED', dataField: 'lookbook_insert', width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false, editable: false
                },
                {
                    text: 'MODIFIELD', dataField: 'lookbook_update', width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false, editable: false
                }
            ];

            $(_CONFIG.JQXGRID).jqxGrid({
                width: '100%', //autoheight:true,
                //height: '100%',
                source: dataAdapter,
                theme: theme,
                columns: columns,
                selectionmode: 'singlecell',
                editmode: 'dblclick',
                editable: true,
                handlekeyboardnavigation: function(event)
                {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (key == 27) {
                        that.cancel = true;
                    }
                },
            }).bind('cellbeginedit', function(event) {
                that.cancel = false;
            }).bind('cellendedit', function(event) {
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                if (that.cancel)
                    return;
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                try {
                    var args = event.args;
                    var column = args.datafield, _row = args.rowindex, _value = args.value;
                    var _data = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', _row);
                    var _id = _data.lookbook_id;
                    if (_id == undefined || _id == "") {
                        return;
                    }
                    switch (column) {
                        case 'Title':
                            if (_value != _data.Title && _value != '')
                                _CP.onCommit({Title: _value}, _id);
                            break;
                        case 'Parent':
                            if (_value != _data.Parent)
                                _CP.onCommit({Parent: _value}, _id, function() {
                                    _CP.onRefresh();
                                });
                            break;
                        case 'lookbook_position':
                            if (_value != _data.block_position)
                                _CP.onCommit({block_position: _value}, _id);
                            break;
                        case 'lookbook_status':
                            if (_value)
                                _CP.onCommit({lookbook_status: 'true'}, _id);
                            else
                                _CP.onCommit({lookbook_status: 'false'}, _id);
                            break;
                        default:
                            $.jGrowl("Chưa mở tính năng sửa trực tiếp cột này", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }
                } catch (e) {
                    $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    //bckdialog({type:'error'}).open(e.message);
                }
            });
        },
        onInit: function() {
            this.creategrid();
        },
        onAddItem: function() {
            this.onEditItem(0);
        },
        onEditItem: function(Id) {
            if (PENDING)
                return false;
            $('#viewport').hide();
            $('#_edit_panel_insite').show().html('<div class="base_loading" style="display: block;height: 60px"></div>');

            backend({
                url: _CONFIG.EDITPANEL_URI + _CONFIG.TYPE,
                data: {
                    Id: Id
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $('#_edit_panel_insite').html('<span style="color:red">' + rsdata.message + '</span>');
                    } else {
                        $('#_edit_panel_insite').html(rsdata.htmlreponse);
                        $('#_form_edit_panel select').select2();
                        if(rsdata['item'] && rsdata.item['lookbook_area']){
                            for(var i=0;i<rsdata.item.lookbook_area.length;i++){
                                var area = rsdata.item.lookbook_area[i];
                                var div = $('<div class="area-item" data-product_id="'+area.product_id + '"></div>').css({
                                    position: 'absolute',
                                    width: area.width + '%',
                                    height: area.height + '%',
                                    left: area.left + '%',
                                    top: area.top + '%',
                                    border: '1px solid #111',
                                    'background-color':'rgba(0,0,0,.3)',
                                    'color':'#fff'
                                });
                                $('#draggable-parent').append(div);
                                div.html(area.product_title+'<span class="removearea" onclick="_CP.RemoveArea(this)">remove</span>')
                                    .attr('title', area.product_id + '-' + area.product_title);
                                $('img#look_book_image').imgAreaSelect({hide: true});
                                var areaitem = $('\
                                    <div data-product_id="'+area.product_id + '" class="area-lookbook area-item" >\
                                        <div class="">\
                                            '+area.product_title + '\
                                        </div>\
                                        <span onclick="_CP.RemoveArea(this)">×</span>\
                                    </div>\
                                ').data('info', {
                                    width: area.width,
                                    height: area.height,
                                    top: area.top,
                                    left: area.left,
                                    product_id: area.product_id,
                                    product_title:area.product_title
                                });
                                $('.area-items').append(areaitem);
                            }
                        }
                    }
                }
            }).call();
        },
        onSave: function() {
            if ($('#_form_edit_panel').validationEngine('validate') === false)
                return false;
            var Params = $('#_form_edit_panel').serializeObject();
            Params.lookbook_area=$('.area-items .area-item').map(function() {
                return $(this).data('info');
            }).get();
            //console.log(Params);return;
            this.onCommit(Params, $('#Id').val(), function() {
                _CP.onRefresh();
                _CP.onCancel();
            });
            return false;
        },
        onCancel: function() {
            $('#_edit_panel_insite').hide();
            $('#viewport').show();
        },
        onDeleteItem: function(Id) {
            backend_delete(_CONFIG.DELETE_URI, Id, function() {
                _CP.onRefresh();
            });
        },
        onRefresh: function() {
            $(_CONFIG.JQXGRID).jqxGrid('updatebounddata');
        },
        onSelectImage: function() {
            BrowseServerCallBack(function(url) {
                $('#lookbook_image').val(url);
                /*$('.draggable').jqxDragDrop({ 
                 restricter: 'parent',  dropTarget: '.drop-target' ,
                 revert:true
                 });*/
                //$( ".draggable" ).draggable({ containment: "#draggable-parent", scroll: false })
                $(".resizable").resizable();
                $('img#look_book_image')
                        .attr('src', url);
            });
        },
        RemoveArea:function(_e){
            var $e = $(_e).parents('.area-item');
            var product_id = $e.data('product_id');
            $('.area-item[data-product_id="'+product_id+'"]').remove();
        },
        InitArea:function(){
                var h, w = 224;
                
                h = $('img#look_book_image').height();
                $('#draggable-parent').css({height: h});
                $('img#look_book_image')
                        .imgAreaSelect({
                    handles: false, hide: true,
                    onSelectEnd: function(img, selection) {
                        console.log(selection);
                        if(selection.width<10 || selection.height<10) return;
                        var _width = selection.width / w * 100,
                                _height = selection.height / h * 100,
                                _marginLeft = selection.x1 / w * 100,
                                _marginTop = selection.y1 / h * 100;
                            


                        CHOOSE_PR.onOpenPopup(function(pr) {
                            var div = $('<div class="area-item" data-product_id="'+pr.product_id + '"></div>').css({
                                position: 'absolute',
                                width: _width + '%',
                                height: _height + '%',
                                left: _marginLeft + '%',
                                top: _marginTop + '%',
                                border: '1px solid #111',
                                'background-color':'rgba(0,0,0,.3)',
                                'color':'#fff'
                            });
                            $('#draggable-parent').append(div);
                            div.html(pr.product_title+'<span class="removearea" onclick="_CP.RemoveArea(this)">remove</span>')
                                .attr('title', pr.product_id + '-' + pr.product_title);
                            $('img#look_book_image').imgAreaSelect({hide: true});
                            var areaitem = $('\
                                <div data-product_id="'+pr.product_id + '" class="area-lookbook area-item" >\
                                    <div class="">\
                                        '+pr.product_title + '\
                                    </div>\
                                    <span onclick="_CP.RemoveArea(this)">×</span>\
                                </div>\
                            ').data('info', {
                                width: _width,
                                height: _height,
                                top: _marginTop,
                                left: _marginLeft,
                                product_id: pr.product_id,
                                product_title:pr.product_title
                            });
                            $('.area-items').append(areaitem);
                        });
                    }
                });
        }
    };
}());